package com.nengchuan.kbms.dfs.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nengchuan.config.exception.NcException;
import com.nengchuan.kbms.common.AutoWrapper;
import com.nengchuan.kbms.common.PageServiceImpl;
import com.nengchuan.kbms.dfs.entity.dto.DataTagDTO;
import com.nengchuan.kbms.dfs.entity.po.DataTag;
import com.nengchuan.kbms.dfs.dao.DataTagMapper;
import com.nengchuan.kbms.dfs.entity.po.DataTagAttr;
import com.nengchuan.kbms.dfs.entity.po.DataTagAttrOption;
import com.nengchuan.kbms.dfs.service.DataTagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 标签 服务实现类
 * </p>
 *
 * @author abe
 * @since 2020-04-03
 */
@Service
public class DataTagServiceImpl extends PageServiceImpl<DataTagMapper, DataTag> implements DataTagService {

    @Autowired
    private DataTagAttrService dataTagAttrService;

    /**
     * 新增标签类型：
     * 1. 检查类型名称是否存在，存在不允许新增
     */
    @Override
    public Long saveTag(DataTagDTO dto) {
        Objects.requireNonNull(dto);
        QueryWrapper<DataTag> wrapper = new AutoWrapper<>(dto);
        DataTag dataTag = getOne(wrapper, false);
        if (dataTag != null) {
            throw new NcException("新增失败，元数据类型已存在");
        }
        return insert(dto).getId();
    }

    /**
     * 更新元数据类型
     */
    @Override
    public boolean updateTag(DataTagDTO dto) {
        Objects.requireNonNull(dto);
        Objects.requireNonNull(dto.getId(), "主键不能为空");

        QueryWrapper<DataTag> wrapper = new AutoWrapper<>(dto);
        wrapper.lambda().ne(DataTag::getId, dto.getId());
        DataTag dataTag = getOne(wrapper, false);
        if (dataTag != null) {
            throw new NcException("修改失败，元数据类型已存在");
        }
        return update(dto);
    }

    /**
     * 删除元数据类型：
     * 1. 检查元数据类型下是否有元数据属性，如果有不允许删除
     */
    @Override
    public boolean removeTag(Long id) {
        QueryWrapper<DataTagAttr> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(DataTagAttr::getTagId, id);
        DataTagAttr dataTagAttr = dataTagAttrService.getOne(wrapper, false);
        if (dataTagAttr != null) {
            throw new NcException("该元数据类型下存在元数据属性，无法删除");
        }
        return removeById(id);
    }

}
